package org.example.day20240904.emp;

import org.example.day20240904.JDBCUtils;
import org.example.day20240904.Scott.Scott;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class empInsert {
    public static void main(String[] args) throws IOException, SQLException {
        FileReader fileReader = new FileReader("emp.txt");
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        Connection connection = JDBCUtils.getConnection();

        String line = bufferedReader.readLine();
        List<emp> empList = new ArrayList<>();
        while (line != null){
            String[] strArr = line.split(",");
            emp emp = new emp(Integer.parseInt(strArr[0])
                    ,strArr[1]
                    ,strArr[2],
                    Integer.parseInt(strArr[3])
                    ,strArr[4]
                    ,Double.parseDouble(strArr[5])
                    ,Double.parseDouble(strArr[6])
                    ,Integer.parseInt(strArr[7]));
            empList.add(emp);
            line = bufferedReader.readLine();
        }
        double sum = 0.0;
        double avg = 0.0;
        for (emp emp : empList){
            sum += emp.getSal();
        }
        avg = sum/empList.size();

        Collections.sort(empList);
        String sql = "insert into emp (ENAME,JOB,MGR,HIREDATE,SAL,COMM,deptno) values(?,?,?,?,?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (emp emp : empList){
            if(emp.getSal() < avg){
                emp.setSal(emp.getSal()+1000.0);
                preparedStatement.setString(1,emp.getName());
                preparedStatement.setString(2,emp.getJob());
                preparedStatement.setInt(3,emp.getMgr());
                preparedStatement.setString(4,emp.getHireDate());
                preparedStatement.setDouble(5,emp.getSal());
                preparedStatement.setDouble(6,emp.getComm());
                preparedStatement.setInt(7,emp.getDeptNo());
                preparedStatement.executeUpdate();
            }
        }
        JDBCUtils.close(connection,preparedStatement);
        bufferedReader.close();
        fileReader.close();
    }
}
